import { VxeUI } from 'vxe-pc-ui';
import RaDict from '@/components/raiseinfo/RaDict/index.vue';
import RaDictLabel from '@/components/raiseinfo/RaDictLabel/index.vue';
import { getNestedPropertyValue } from './utils';

/**
 * 提取code属性的通用函数
 * @param {Object} renderOpts - 渲染选项
 * @param {Object} itemRender - 项目渲染配置
 * @param {Object} props - 属性对象
 * @param {Object} attrs - 特性对象
 * @returns {string|null} code值
 */
const extractCode = (renderOpts, itemRender = {}, props = {}, attrs = {}) => {
  return (
    props.code ||
    attrs.code ||
    renderOpts.code ||
    renderOpts.options?.code ||
    renderOpts.config?.code ||
    itemRender.code ||
    null
  );
};

/**
 * 获取属性值的通用函数
 * @param {string} attrName - 属性名
 * @param {*} defaultValue - 默认值
 * @param {Object} sources - 属性来源对象数组
 * @returns {*} 属性值
 */
const getAttributeValue = (attrName, defaultValue, ...sources) => {
  for (const source of sources) {
    if (source && source[attrName] !== undefined) {
      return source[attrName];
    }
  }
  return defaultValue;
};

/**
 * 渲染字典标签的通用函数（用于显示模式）
 * @param {Object} renderOpts - 渲染选项
 * @param {Object} params - 参数对象
 * @returns {JSX.Element} 渲染结果
 */
const renderDictLabel = (renderOpts, params) => {
  // 确定有效的数据和列上下文
  const effectiveData = params?.row || renderOpts.row || renderOpts.data || {};
  const effectiveColumn = params?.column || renderOpts.column || {};

  // 获取字段名
  const field =
    effectiveColumn.field || effectiveColumn.property || params?.field;

  if (!field) {
    console.warn('RaDictRender: Missing field identifier in display mode');
    return <span>-</span>;
  }

  // 获取当前值
  // const value = effectiveData[field];
  // 获取当前值，使用辅助函数支持多层属性访问
  const value = getNestedPropertyValue(effectiveData, field);

  // 获取配置信息
  const props = renderOpts.props || {};
  const attrs = renderOpts.attrs || {};

  // 提取code属性
  const code = extractCode(renderOpts, {}, props, attrs);

  if (!code) {
    console.error(
      'RaDictRender: Missing required "code" prop for dictionary label',
    );
    return (
      <div style={{ color: 'red', padding: '4px', fontSize: '12px' }}>
        缺少字典代码
      </div>
    );
  }

  // 返回RaDictLabel组件
  return (
    <RaDictLabel
      modelValue={value}
      code={code}
      perms={getAttributeValue('perms', false, props, attrs, renderOpts)}
      type={getAttributeValue('type', 'primary', props, attrs, renderOpts)}
      separation={getAttributeValue(
        'separation',
        ',',
        props,
        attrs,
        renderOpts,
      )}
    />
  );
};

/**
 * 通用渲染逻辑函数（用于编辑模式）
 * @param {Object} renderOpts - 渲染选项
 * @param {Object} params - 参数对象
 * @returns {JSX.Element} 渲染结果
 */
const renderRaDict = (renderOpts, params) => {
  // 确定有效的数据和项上下文
  const effectiveData = params?.row || params?.data || renderOpts.data || {};
  const effectiveItem = params?.item || renderOpts.item || {};
  const effectiveColumn = params?.column || {};

  // 确定字段名
  const field =
    params?.field ||
    effectiveColumn.field ||
    effectiveItem.field ||
    renderOpts.field;

  if (!field) {
    console.error('RaDictRender: Missing field identifier in edit mode');
    return null;
  }

  // 获取当前值
  const value = effectiveData[field];

  // 从effectiveItem中获取配置信息
  const itemRender = effectiveItem.itemRender || {};
  const props = itemRender.props || renderOpts.props || {};
  const attrs = itemRender.attrs || renderOpts.attrs || {};
  const events = itemRender.events || renderOpts.events || {};

  const title = effectiveColumn.title || effectiveItem.title || '';

  // 事件处理器
  const updateValue = (val) => {
    // 更新数据
    if (params?.row) {
      params.row[field] = val;
    } else if (params?.data) {
      params.data[field] = val;
    } else if (renderOpts.data) {
      renderOpts.data[field] = val;
    }

    // 触发原始事件
    events.change?.(val, effectiveData, params || renderOpts);
  };

  // 提取code属性
  const code = extractCode(renderOpts, itemRender, props, attrs);

  if (!code) {
    console.error('RaDictRender: Missing required "code" prop for dictionary');
    return (
      <div style={{ color: 'red', padding: '8px', border: '1px solid red' }}>
        缺少字典代码配置
      </div>
    );
  }

  // 返回RaDict组件
  return (
    <RaDict
      modelValue={value}
      onUpdate:modelValue={updateValue}
      code={code}
      type={getAttributeValue(
        'type',
        'select',
        props,
        attrs,
        itemRender,
        renderOpts,
      )}
      disabled={getAttributeValue(
        'disabled',
        renderOpts.disabled || false,
        props,
        attrs,
        itemRender,
        renderOpts,
      )}
      placeholder={getAttributeValue(
        'placeholder',
        undefined,
        props,
        attrs,
        itemRender,
        renderOpts,
      )}
      multiple={getAttributeValue(
        'multiple',
        false,
        props,
        attrs,
        itemRender,
        renderOpts,
      )}
      perms={getAttributeValue(
        'perms',
        false,
        props,
        attrs,
        itemRender,
        renderOpts,
      )}
      color={getAttributeValue(
        'color',
        false,
        props,
        attrs,
        itemRender,
        renderOpts,
      )}
      style={getAttributeValue(
        'style',
        {},
        props,
        attrs,
        itemRender,
        renderOpts,
      )}
      // 开关属性配置
      switchActiveValue={getAttributeValue(
        'switchActiveValue',
        true,
        props,
        attrs,
        itemRender,
        renderOpts,
      )}
      switchInactiveValue={getAttributeValue(
        'switchInactiveValue',
        false,
        props,
        attrs,
        itemRender,
        renderOpts,
      )}
      switchActiveText={getAttributeValue(
        'switchActiveText',
        '开启',
        props,
        attrs,
        itemRender,
        renderOpts,
      )}
      switchInactiveText={getAttributeValue(
        'switchInactiveText',
        '关闭',
        props,
        attrs,
        itemRender,
        renderOpts,
      )}
      // 穿梭框配置
      transferTitles={getAttributeValue(
        'transferTitles',
        ['待选项', '已选项'],
        props,
        attrs,
        itemRender,
        renderOpts,
      )}
      transferFormat={getAttributeValue(
        'transferFormat',
        {
          noChecked: '${total}',
          hasChecked: '${checked}/${total}',
        },
        props,
        attrs,
        itemRender,
        renderOpts,
      )}
    />
  );
};

// 注册支持多种上下文的渲染器
VxeUI.renderer.add('RaDictRender', {
  // 表格单元格编辑模式
  renderTableEdit(renderOpts, params) {
    return renderRaDict(renderOpts, params);
  },

  // 表格单元格显示模式
  renderTableCell(renderOpts, params) {
    return renderDictLabel(renderOpts, params);
  },

  // 表单项目渲染
  renderItemContent(renderOpts, params) {
    return renderRaDict(renderOpts, params);
  },

  // 默认显示模式（与renderTableCell相同）
  renderDefault(renderOpts, params) {
    return renderDictLabel(renderOpts, params);
  },
});

export default 'RaDictRender';
